package br.mikhas.task.application;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import br.mikhas.util.Assert;

/**
 * Exceptions used to agregate a series of other exceptions
 * 
 * @author Mikhail Domanoski
 * 
 */
public class CollectedException extends ApplicationRuntimeException {

	private static final long serialVersionUID = 5957200922017153904L;
	/**
	 * The exception collection
	 */
	private final Collection<Exception> exceptions = new ArrayList<Exception>();

	public CollectedException(String message) {
		super(message);
	}

	/**
	 * Collects a new Exception
	 * 
	 * @param exception
	 *            exception to be collected
	 */
	public void collect(Exception exception) {
		Assert.notNull(exception);
		if (exception == this)
			return;

		if (!this.exceptions.contains(exception))
			exceptions.add(exception);
	}

	/**
	 * Throws this exception if it have collected any other exception
	 */
	public void throwIfElegible() {
		if (!this.exceptions.isEmpty())
			throw this;
	}

	/**
	 * Gets exceptions collected by this exception
	 * 
	 * @return
	 */
	public Collection<Exception> getCollectedExceptions() {
		if (this.exceptions.isEmpty())
			return Collections.emptyList();
		else
			return Collections.unmodifiableCollection(this.exceptions);
	}
}
